package com.basic.modules.ykf.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.basic.common.exception.RRException;
import com.basic.common.validator.ValidatorUtils;
import com.basic.modules.sys.controller.AbstractController;
import com.basic.modules.sys.entity.SysRoleEntity;
import com.basic.modules.sys.entity.SysUserEntity;
import com.basic.modules.sys.entity.SysUserRoleEntity;
import com.basic.modules.sys.service.SysRoleService;
import com.basic.modules.sys.service.SysUserRoleService;
import com.basic.modules.ykf.entity.YkfCompanyDeptEntity;
import com.basic.modules.ykf.entity.YkfCustomGroupEntity;
import com.basic.modules.ykf.entity.YkfDictEntity;
import com.basic.modules.ykf.service.YkfCompanyDeptService;
import com.basic.modules.ykf.service.YkfCustomGroupService;
import com.basic.modules.ykf.service.YkfDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.basic.modules.ykf.entity.YkfDictDetailEntity;
import com.basic.modules.ykf.service.YkfDictDetailService;
import com.basic.common.utils.R;

/**
 * 字典详情
 *
 * @author maoheng
 * @email 15738859597@163.com
 * @date 2024-03-20 09:22:08
 */
@RestController
@RequestMapping("ykf/dictDetail")
public class YkfDictDetailController extends AbstractController {

    @Autowired
    private YkfDictDetailService ykfDictDetailService;

    @Autowired
    private YkfDictService ykfDictService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private YkfCompanyDeptService companyDeptService;

    @Autowired
    private YkfCustomGroupService customGroupService;

    /**
     * 列表
     */
    @PostMapping("/list")
    public R list(@RequestBody YkfDictDetailEntity params) {
        if (ObjectUtil.isNotEmpty(params) && ObjectUtil.isNotEmpty(params.getDictId())) {
            QueryWrapper<YkfDictDetailEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(YkfDictDetailEntity::getDictId, params.getDictId())
                    .orderByAsc(YkfDictDetailEntity::getSort);
            return R.ok(ykfDictDetailService.list(queryWrapper));
        } else {
            throw new RRException("参数缺失");
        }
    }

    /**
     * 列表
     */
    @PostMapping("/listByNo")
    public R listByNo(@RequestBody YkfDictDetailEntity params) {
        if (ObjectUtil.isNotEmpty(params) && ObjectUtil.isNotEmpty(params.getDictNo())) {
            QueryWrapper<YkfDictEntity> dictQueryWrapper = new QueryWrapper<>();
            dictQueryWrapper.lambda().eq(YkfDictEntity::getDictNo, params.getDictNo());
            dictQueryWrapper.last("limit 1");

            // 取出字典表dict_no为company的数据对象
            YkfDictEntity dict = ykfDictService.getOne(dictQueryWrapper);
            if (ObjectUtil.isNotEmpty(dict)) {
                QueryWrapper<YkfDictDetailEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(YkfDictDetailEntity::getDictId, dict.getDictId())
                        .orderByAsc(YkfDictDetailEntity::getSort);
                // 查询公司时需过滤权限
                if (StrUtil.equals(params.getDictNo(), "company")) {
                    SysUserEntity user = getUser();
                    if (ObjectUtil.isNotEmpty(user) && !StrUtil.equals(user.getUsername(), "admin")) {
                        // 查询用户所有的角色公司
                        QueryWrapper<SysUserRoleEntity> queryWrapper1 = new QueryWrapper<>();
                        queryWrapper1.lambda().eq(SysUserRoleEntity::getUserId, user.getUserId());
                        List<SysUserRoleEntity> list = sysUserRoleService.list(queryWrapper1);
                        if (ObjectUtil.isNotEmpty(list)) {
                            // 取出这个用户的所有角色
                            List<Long> roleIds = list.stream().map(SysUserRoleEntity::getRoleId).collect(Collectors.toList());
                            List<SysRoleEntity> roleEntityList = sysRoleService.listByIds(roleIds);
                            if (ObjectUtil.isNotEmpty(roleEntityList)) {
                                List<String> companyPerms = roleEntityList.stream().map(SysRoleEntity::getCompanyPerms).collect(Collectors.toList());
                                if (!companyPerms.contains("ALL")) {
                                    queryWrapper.lambda().in(YkfDictDetailEntity::getVal, companyPerms);
                                }
                            }
                        }
                    }
                } else if (StrUtil.equals(params.getDictNo(), "department")) {
                    //查询公司部门
                    SysUserEntity user = getUser();
                    if (ObjectUtil.isNotEmpty(user)) {
                        if (!StrUtil.equals(user.getUsername(), "admin")) {
                            if (StrUtil.isNotBlank(params.getCompanyNo())) {
                                //查询对应企业的部门
                                QueryWrapper<YkfCompanyDeptEntity> queryWrapper2 = new QueryWrapper<>();
                                queryWrapper2.lambda().eq(YkfCompanyDeptEntity::getCompanyNo, params.getCompanyNo());
                                List<YkfCompanyDeptEntity> list1 = companyDeptService.list(queryWrapper2);
                                if (ObjectUtil.isNotEmpty(list1)) {
                                    List<YkfDictDetailEntity> list2 = new ArrayList<>();
                                    for (YkfCompanyDeptEntity item : list1) {
                                        YkfDictDetailEntity detail = new YkfDictDetailEntity();
                                        detail.setVal(StrUtil.toString(item.getDeptId()));
                                        detail.setName(item.getDeptName());
                                        list2.add(detail);
                                    }
                                    return R.ok(list2);
                                }
                            } else {
                                //查询用户所有的角色公司
                                QueryWrapper<SysUserRoleEntity> queryWrapper1 = new QueryWrapper<>();
                                queryWrapper1.lambda().eq(SysUserRoleEntity::getUserId, user.getUserId());
                                List<SysUserRoleEntity> list = sysUserRoleService.list(queryWrapper1);
                                if (ObjectUtil.isNotEmpty(list)) {
                                    List<Long> roleIds = list.stream().map(SysUserRoleEntity::getRoleId).collect(Collectors.toList());
                                    List<SysRoleEntity> roleEntityList = sysRoleService.listByIds(roleIds);
                                    if (ObjectUtil.isNotEmpty(roleEntityList)) {
                                        List<String> companyPerms = roleEntityList.stream().map(SysRoleEntity::getCompanyPerms).collect(Collectors.toList());
                                        //查询对应企业的部门
                                        QueryWrapper<YkfCompanyDeptEntity> queryWrapper2 = new QueryWrapper<>();
                                        queryWrapper2.lambda().in(YkfCompanyDeptEntity::getCompanyNo, companyPerms);
                                        List<YkfCompanyDeptEntity> list1 = companyDeptService.list(queryWrapper2);
                                        if (ObjectUtil.isNotEmpty(list1)) {
                                            List<YkfDictDetailEntity> list2 = new ArrayList<>();
                                            for (YkfCompanyDeptEntity item : list1) {
                                                YkfDictDetailEntity detail = new YkfDictDetailEntity();
                                                detail.setVal(StrUtil.toString(item.getDeptId()));
                                                detail.setName(item.getDeptName());
                                                list2.add(detail);
                                            }
                                            return R.ok(list2);
                                        }
                                    }
                                }
                            }

                        } else {
                            QueryWrapper<YkfCompanyDeptEntity> queryWrapper2 = new QueryWrapper<>();
                            if (StrUtil.isNotBlank(params.getCompanyNo())) {
                                //查询对应企业的部门
                                queryWrapper2.lambda().eq(YkfCompanyDeptEntity::getCompanyNo, params.getCompanyNo());
                            }
                            List<YkfCompanyDeptEntity> list1 = companyDeptService.list(queryWrapper2);
                            if (ObjectUtil.isNotEmpty(list1)) {
                                List<YkfDictDetailEntity> list2 = new ArrayList<>();
                                for (YkfCompanyDeptEntity item : list1) {
                                    YkfDictDetailEntity detail = new YkfDictDetailEntity();
                                    detail.setVal(StrUtil.toString(item.getDeptId()));
                                    detail.setName(item.getDeptName());
                                    list2.add(detail);
                                }
                                return R.ok(list2);
                            }
                            return R.ok(new ArrayList<>());
                        }
                    }
                    return R.ok(new ArrayList<>());
                }
                if (StrUtil.equals(params.getDictNo(), "customGroup")) {
                    //查询公司部门
                    SysUserEntity user = getUser();
                    if (ObjectUtil.isNotEmpty(user)) {
                        if (!StrUtil.equals(user.getUsername(), "admin")) {
                            if (StrUtil.isNotBlank(params.getCompanyNo())) {
                                //查询对应企业的部门
                                QueryWrapper<YkfCustomGroupEntity> queryWrapper2 = new QueryWrapper<>();
                                queryWrapper2.lambda().eq(YkfCustomGroupEntity::getCompanyNo, params.getCompanyNo());
                                List<YkfCustomGroupEntity> list1 = customGroupService.list(queryWrapper2);
                                if (ObjectUtil.isNotEmpty(list1)) {
                                    List<YkfDictDetailEntity> list2 = new ArrayList<>();
                                    for (YkfCustomGroupEntity item : list1) {
                                        YkfDictDetailEntity detail = new YkfDictDetailEntity();
                                        detail.setVal(StrUtil.toString(item.getCustomGroupId()));
                                        detail.setName(item.getCustomGroupName());
                                        list2.add(detail);
                                    }
                                    return R.ok(list2);
                                }
                            } else {
                                //查询用户所有的角色公司
                                QueryWrapper<SysUserRoleEntity> queryWrapper1 = new QueryWrapper<>();
                                queryWrapper1.lambda().eq(SysUserRoleEntity::getUserId, user.getUserId());
                                List<SysUserRoleEntity> list = sysUserRoleService.list(queryWrapper1);
                                if (ObjectUtil.isNotEmpty(list)) {
                                    List<Long> roleIds = list.stream().map(SysUserRoleEntity::getRoleId).collect(Collectors.toList());
                                    List<SysRoleEntity> roleEntityList = sysRoleService.listByIds(roleIds);
                                    if (ObjectUtil.isNotEmpty(roleEntityList)) {
                                        List<String> companyPerms = roleEntityList.stream().map(SysRoleEntity::getCompanyPerms).collect(Collectors.toList());
                                        //查询对应企业的部门
                                        QueryWrapper<YkfCustomGroupEntity> queryWrapper2 = new QueryWrapper<>();
                                        queryWrapper2.lambda().in(YkfCustomGroupEntity::getCompanyNo, companyPerms);
                                        List<YkfCustomGroupEntity> list1 = customGroupService.list(queryWrapper2);
                                        if (ObjectUtil.isNotEmpty(list1)) {
                                            List<YkfDictDetailEntity> list2 = new ArrayList<>();
                                            for (YkfCustomGroupEntity item : list1) {
                                                YkfDictDetailEntity detail = new YkfDictDetailEntity();
                                                detail.setVal(StrUtil.toString(item.getCustomGroupId()));
                                                detail.setName(item.getCustomGroupName());
                                                list2.add(detail);
                                            }
                                            return R.ok(list2);
                                        }
                                    }
                                }
                            }

                        } else {
                            QueryWrapper<YkfCustomGroupEntity> queryWrapper2 = new QueryWrapper<>();
                            if (StrUtil.isNotBlank(params.getCompanyNo())) {
                                //查询对应企业的部门
                                queryWrapper2.lambda().eq(YkfCustomGroupEntity::getCompanyNo, params.getCompanyNo());
                            }
                            List<YkfCustomGroupEntity> list1 = customGroupService.list(queryWrapper2);
                            if (ObjectUtil.isNotEmpty(list1)) {
                                List<YkfDictDetailEntity> list2 = new ArrayList<>();
                                for (YkfCustomGroupEntity item : list1) {
                                    YkfDictDetailEntity detail = new YkfDictDetailEntity();
                                    detail.setVal(StrUtil.toString(item.getCustomGroupId()));
                                    detail.setName(item.getCustomGroupName());
                                    list2.add(detail);
                                }
                                return R.ok(list2);
                            }
                            return R.ok(new ArrayList<>());
                        }
                    }
                    return R.ok(new ArrayList<>());
                }
                return R.ok(ykfDictDetailService.list(queryWrapper));
            }
        } else {
            throw new RRException("参数缺失");
        }
        return R.ok(new ArrayList<>());
    }
    @PostMapping("/findByNo")
    public R findByNo(@RequestBody YkfDictDetailEntity params) {
        if (ObjectUtil.isNotEmpty(params) && ObjectUtil.isNotEmpty(params.getDictNo())) {
            QueryWrapper<YkfDictEntity> dictQueryWrapper = new QueryWrapper<>();
            dictQueryWrapper.lambda().eq(YkfDictEntity::getDictNo, params.getDictNo());
            dictQueryWrapper.last("limit 1");
            // 取出字典表dict_no为company的数据对象
            YkfDictEntity dict = ykfDictService.getOne(dictQueryWrapper);
            QueryWrapper<YkfDictDetailEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(YkfDictDetailEntity::getDictId, dict.getDictId())
                    .orderByAsc(YkfDictDetailEntity::getSort);
        }else {
            throw new RRException("参数缺失");
        }
        return R.ok(new ArrayList<>());
    }
    /**
     * 列表
     */
    @PostMapping("/getDepartment")
    @ResponseBody
    public R getDepartment(@RequestBody YkfDictDetailEntity params) {
        List<YkfDictDetailEntity> list2 = new ArrayList<>();
        //查询公司部门
        SysUserEntity user = getUser();
        if (ObjectUtil.isNotEmpty(user)) {
            if (!StrUtil.equals(user.getUsername(), "admin")) {
                if (StrUtil.isNotBlank(params.getCompanyNo())) {
                    //查询对应企业的部门
                    QueryWrapper<YkfCompanyDeptEntity> queryWrapper2 = new QueryWrapper<>();
                    queryWrapper2.lambda().eq(YkfCompanyDeptEntity::getCompanyNo, params.getCompanyNo());
                    List<YkfCompanyDeptEntity> list1 = companyDeptService.list(queryWrapper2);
                    if (ObjectUtil.isNotEmpty(list1)) {

                        for (YkfCompanyDeptEntity item : list1) {
                            YkfDictDetailEntity detail = new YkfDictDetailEntity();
                            detail.setVal(StrUtil.toString(item.getDeptId()));
                            detail.setName(item.getDeptName());
                            list2.add(detail);
                        }
                    }
                } else {
                    //查询用户所有的角色公司
                    QueryWrapper<SysUserRoleEntity> queryWrapper1 = new QueryWrapper<>();
                    queryWrapper1.lambda().eq(SysUserRoleEntity::getUserId, user.getUserId());
                    List<SysUserRoleEntity> list = sysUserRoleService.list(queryWrapper1);
                    if (ObjectUtil.isNotEmpty(list)) {
                        List<Long> roleIds = list.stream().map(SysUserRoleEntity::getRoleId).collect(Collectors.toList());
                        List<SysRoleEntity> roleEntityList = sysRoleService.listByIds(roleIds);
                        if (ObjectUtil.isNotEmpty(roleEntityList)) {
                            List<String> companyPerms = roleEntityList.stream().map(SysRoleEntity::getCompanyPerms).collect(Collectors.toList());
                            //查询对应企业的部门
                            QueryWrapper<YkfCompanyDeptEntity> queryWrapper2 = new QueryWrapper<>();
                            queryWrapper2.lambda().in(YkfCompanyDeptEntity::getCompanyNo, companyPerms);
                            List<YkfCompanyDeptEntity> list1 = companyDeptService.list(queryWrapper2);
                            if (ObjectUtil.isNotEmpty(list1)) {
                                for (YkfCompanyDeptEntity item : list1) {
                                    YkfDictDetailEntity detail = new YkfDictDetailEntity();
                                    detail.setVal(StrUtil.toString(item.getDeptId()));
                                    detail.setName(item.getDeptName());
                                    list2.add(detail);
                                }
                            }
                        }
                    }
                }

            } else {
                QueryWrapper<YkfCompanyDeptEntity> queryWrapper2 = new QueryWrapper<>();
                if (StrUtil.isNotBlank(params.getCompanyNo())) {
                    //查询对应企业的部门
                    queryWrapper2.lambda().eq(YkfCompanyDeptEntity::getCompanyNo, params.getCompanyNo());
                }
                List<YkfCompanyDeptEntity> list1 = companyDeptService.list(queryWrapper2);
                if (ObjectUtil.isNotEmpty(list1)) {
                    for (YkfCompanyDeptEntity item : list1) {
                        YkfDictDetailEntity detail = new YkfDictDetailEntity();
                        detail.setVal(StrUtil.toString(item.getDeptId()));
                        detail.setName(item.getDeptName());
                        list2.add(detail);
                    }
                }
            }
        }
        if (list2.size() > 0) {
            List<YkfDictDetailEntity> resList = new ArrayList<>();
            for (YkfDictDetailEntity item : list2) {
                if (StrUtil.equals(item.getName(), "市场部")) {
                    resList.add(0, item);
                } else {
                    resList.add(item);
                }
            }
            return R.ok(resList);
        } else {
            return R.ok(list2);
        }
    }

    /**
     * 排序
     */
    @PostMapping("/sortDetail")
    public R sortDetail(@RequestBody YkfDictEntity params) {
        if (ObjectUtil.isEmpty(params) || ObjectUtil.isEmpty(params.getDictDetailList())) {
            throw new RRException("参数缺失");
        }
        List<YkfDictDetailEntity> detailList = params.getDictDetailList();
        QueryWrapper<YkfDictDetailEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(YkfDictDetailEntity::getDictId, detailList.get(0).getDictId());
        ykfDictDetailService.remove(queryWrapper);
        for (int i = 0; i < detailList.size(); i++) {
            YkfDictDetailEntity detail = detailList.get(i);
            detail.setDictDetailId(null);
            detail.setSort(i + 1);
        }
        ykfDictDetailService.saveBatch(detailList);
        return R.ok();
    }


    /**
     * 信息
     */
    @PostMapping("/info")
    public R info(@RequestBody YkfDictDetailEntity params) {
        if (ObjectUtil.isEmpty(params) || ObjectUtil.isEmpty(params.getDictDetailId())) {
            throw new RRException("参数缺失");
        }
        return R.ok(ykfDictDetailService.getById(params.getDictDetailId()));
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    public R save(@RequestBody YkfDictDetailEntity ykfDictDetail) {
        ValidatorUtils.validateEntity(ykfDictDetail);
        QueryWrapper<YkfDictDetailEntity> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(YkfDictDetailEntity::getDictId, ykfDictDetail.getDictId())
                .and(wrapper -> wrapper.eq(YkfDictDetailEntity::getVal, ykfDictDetail.getVal())
                        .or().eq(YkfDictDetailEntity::getName, ykfDictDetail.getName()));
        if (ykfDictDetailService.count(queryWrapper1) > 0) {
            throw new RRException("值或名称已存在，请检查");
        }
        //查询count
        QueryWrapper<YkfDictDetailEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(YkfDictDetailEntity::getDictId, ykfDictDetail.getDictId());
        int count = ykfDictDetailService.count(queryWrapper);
        ykfDictDetail.setSort(count + 1);
        ykfDictDetailService.save(ykfDictDetail);
        YkfDictEntity dict = ykfDictService.getById(ykfDictDetail.getDictId());
        if (ObjectUtil.isNotEmpty(dict)) {
            ykfDictDetailService.updateDictMap(dict.getDictNo(), ykfDictDetail.getVal(), ykfDictDetail.getName());
        }
        return R.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    public R update(@RequestBody YkfDictDetailEntity ykfDictDetail) {
        ValidatorUtils.validateEntity(ykfDictDetail);
        QueryWrapper<YkfDictDetailEntity> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(YkfDictDetailEntity::getDictId, ykfDictDetail.getDictId())
                .and(wrapper -> wrapper.eq(YkfDictDetailEntity::getVal, ykfDictDetail.getVal())
                        .or().eq(YkfDictDetailEntity::getName, ykfDictDetail.getName()))
                .ne(YkfDictDetailEntity::getDictDetailId, ykfDictDetail.getDictDetailId());
        if (ykfDictDetailService.count(queryWrapper1) > 0) {
            throw new RRException("值或名称已存在，请检查");
        }
        ykfDictDetailService.updateById(ykfDictDetail);
        YkfDictEntity dict = ykfDictService.getById(ykfDictDetail.getDictId());
        if (ObjectUtil.isNotEmpty(dict)) {
            ykfDictDetailService.updateDictMap(dict.getDictNo(), ykfDictDetail.getVal(), ykfDictDetail.getName());
        }
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    public R delete(@RequestBody Long[] dictDetailIds) {
        List<YkfDictDetailEntity> list = ykfDictDetailService.listByIds(Arrays.asList(dictDetailIds));
        ykfDictDetailService.removeByIds(Arrays.asList(dictDetailIds));
        if (ObjectUtil.isNotEmpty(list)) {
            for (YkfDictDetailEntity item : list) {
                YkfDictEntity dict = ykfDictService.getById(item.getDictId());
                if (ObjectUtil.isNotEmpty(dict)) {
                    ykfDictDetailService.updateDictMap(dict.getDictNo(), item.getVal(), "");
                }
            }
        }
        return R.ok();
    }

}
